var instance;

function YouTubePlayerEvents(playerId, videoDivId, videoUrl, width, height) {

    this.id = playerId;
    this.videoUrl = videoUrl;
    this.videoDivId = videoDivId;
    this.width = width;
    this.height = height;

}

//decorate YouTube
YouTubePlayerEvents.prototype = {
    youTubeEvents : new Array(),

    addEvent : function(eventId, eventTime, eventCallBackFunction) {

        this.youTubeEvents.push(new YouTubeEvent(eventId, eventTime, eventCallBackFunction));
    },

    getEvents : function () {

        return this.youTubeEvents;
    }
}

function embedSWF(instanceRef) {

    instance = instanceRef;

    var params = { allowScriptAccess: "always" };

    var atts = { id: instance.id};

    swfobject.embedSWF(instance.videoUrl + "&amp;border=0&amp;enablejsapi=1&amp;playerapiid=" + instance.id,
            instance.videoDivId, instance.width, instance.height, "8", null, null, params, atts);


}

function broadcastEvents(ytPlayer) {

    if(ytPlayer.getPlayerState() == 1) {

        currentTime = ytPlayer.getCurrentTime();

        for( index in instance.youTubeEvents) {

            e = instance.youTubeEvents[index];
            if(e.dirty) {

                if(e.eventTime <= currentTime + 2) {
                    e.dirty = false;
                    e.onBroadcast(e);
                }
            }

        }

    }
}

function YouTubeEvent(eventId, eventTime, eventCallBackFunction) {

    this.eventId = eventId;
    this.eventTime = eventTime;
    this.dirty = true;

    this.onBroadcast = function(youTubeEvent) {

        eventCallBackFunction.call(youTubeEvent);
    }
}

function getYouTubePlayer(playerId) {
    return document.getElementById(playerId);
}

function onYouTubePlayerReady(playerId) {

    setInterval(broadcastEvents,250, getYouTubePlayer(playerId));
}

    function updateHTML(elmId, value) {
        document.getElementById(elmId).innerHTML = value;
    }